const User = require('../models/User');
const jwt = require('jsonwebtoken');
const fs = require('fs');

// 生成JWT令牌
const generateToken = (id) => {
  return jwt.sign({ id }, process.env.JWT_SECRET, {
    expiresIn: '30d',
  });
};

/**
 * @desc    获取用户书签列表
 * @route   GET /api/users/bookmarks
 * @access  私有
 */
const getBookmarks = async (req, res) => {
  try {
    const userId = req.user._id;
    
    // 获取用户信息，包括书签
    const user = await User.findById(userId).populate({
      path: 'bookmarks',
      select: '_id title content chapter difficulty tags sourceDocument createdAt',
      populate: {
        path: 'sourceDocument',
        select: 'title'
      }
    });
    
    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }
    
    console.log(`[getBookmarks] 用户 ${userId} 的书签数量: ${user.bookmarks.length}`);
    
    res.json(user.bookmarks || []);
  } catch (error) {
    console.error('获取书签列表时出错:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

/**
 * @desc    注册新用户
 * @route   POST /api/users/register
 * @access  公开
 */
const registerUser = async (req, res) => {
  try {
    const { username, email, password } = req.body;
    
    // 表单验证
    const errors = {};
    
    // 验证用户名
    if (!username || username.trim().length < 3) {
      errors.username = '用户名至少需要3个字符';
    }
    
    // 验证邮箱
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!email || !emailRegex.test(email)) {
      errors.email = '请提供有效的邮箱地址';
    }
    
    // 验证密码
    if (!password || password.length < 6) {
      errors.password = '密码至少需要6个字符';
    }
    
    // 如果有验证错误，返回400错误
    if (Object.keys(errors).length > 0) {
      return res.status(400).json({
        message: '请检查您的注册信息',
        errors
      });
    }

    // 检查用户是否已存在
    const userExists = await User.findOne({ email });
    if (userExists) {
      return res.status(400).json({ 
        message: '该邮箱已被注册',
        errors: { email: '该邮箱已被注册' }
      });
    }
    
    // 检查用户名是否已存在
    const usernameExists = await User.findOne({ username });
    if (usernameExists) {
      return res.status(400).json({ 
        message: '该用户名已被使用',
        errors: { username: '该用户名已被使用' }
      });
    }

    // 创建新用户
    const user = await User.create({
      username,
      email,
      password,
    });

    if (user) {
      res.status(201).json({
        _id: user._id,
        username: user.username,
        email: user.email,
        token: generateToken(user._id),
      });
    } else {
      res.status(400).json({ 
        message: '无效的用户数据',
        errors: { general: '无法创建用户，请检查您的信息' }
      });
    }
  } catch (error) {
    console.error('注册用户时出错:', error);
    res.status(500).json({ 
      message: '服务器错误，请稍后再试',
      errors: { general: '服务器处理请求时出错' }
    });
  }
};

/**
 * @desc    用户登录
 * @route   POST /api/users/login
 * @access  公开
 */
const loginUser = async (req, res) => {
  try {
    const { email, password } = req.body;

    // 查找用户
    const user = await User.findOne({ email });

    // 检查用户是否存在并验证密码
    if (user && (await user.comparePassword(password))) {
      res.json({
        _id: user._id,
        username: user.username,
        email: user.email,
        token: generateToken(user._id),
      });
    } else {
      res.status(401).json({ message: '邮箱或密码不正确' });
    }
  } catch (error) {
    console.error('用户登录时出错:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

/**
 * @desc    获取用户个人资料
 * @route   GET /api/users/profile
 * @access  私有
 */
const getUserProfile = async (req, res) => {
  try {
    // req.user 由 auth 中间件设置
    const user = await User.findById(req.user._id).select('-password');

    if (user) {
      res.json(user);
    } else {
      res.status(404).json({ message: '用户不存在' });
    }
  } catch (error) {
    console.error('获取用户资料时出错:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

/**
 * @desc    更新用户个人资料
 * @route   PUT /api/users/profile
 * @access  私有
 */
const updateUserProfile = async (req, res) => {
  try {
    const user = await User.findById(req.user._id);

    if (user) {
      user.username = req.body.username || user.username;
      user.email = req.body.email || user.email;

      if (req.body.password) {
        user.password = req.body.password;
      }

      const updatedUser = await user.save();

      res.json({
        _id: updatedUser._id,
        username: updatedUser.username,
        email: updatedUser.email,
        token: generateToken(updatedUser._id),
      });
    } else {
      res.status(404).json({ message: '用户不存在' });
    }
  } catch (error) {
    console.error('更新用户资料时出错:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

/**
 * @desc    添加书签
 * @route   POST /api/users/bookmarks
 * @access  私有
 */
const addBookmark = async (req, res) => {
  try {
    const { cardId } = req.body;
    const user = await User.findById(req.user._id);

    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }

    // 检查是否已经收藏
    if (user.bookmarks.includes(cardId)) {
      return res.status(400).json({ message: '已经收藏了该卡片' });
    }

    // 添加书签
    user.bookmarks.push(cardId);
    await user.save();

    res.status(201).json({ message: '成功添加书签', bookmarks: user.bookmarks });
  } catch (error) {
    console.error('添加书签时出错:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

/**
 * @desc    移除书签
 * @route   DELETE /api/users/bookmarks/:cardId
 * @access  私有
 */
const removeBookmark = async (req, res) => {
  try {
    const { cardId } = req.params;
    const user = await User.findById(req.user._id);

    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }

    // 移除书签
    user.bookmarks = user.bookmarks.filter(
      bookmark => bookmark.toString() !== cardId
    );
    await user.save();

    res.json({ message: '成功移除书签', bookmarks: user.bookmarks });
  } catch (error) {
    console.error('移除书签时出错:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

/**
 * @desc    添加笔记
 * @route   POST /api/users/notes
 * @access  私有
 */
const addNote = async (req, res) => {
  try {
    const { cardId, content } = req.body;
    const user = await User.findById(req.user._id);

    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }

    // 添加笔记
    const note = {
      cardId,
      content,
      createdAt: Date.now(),
      updatedAt: Date.now()
    };

    user.notes.push(note);
    await user.save();

    res.status(201).json({ message: '成功添加笔记', note });
  } catch (error) {
    console.error('添加笔记时出错:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

/**
 * @desc    更新笔记
 * @route   PUT /api/users/notes/:noteId
 * @access  私有
 */
const updateNote = async (req, res) => {
  try {
    const { noteId } = req.params;
    const { content } = req.body;
    const user = await User.findById(req.user._id);

    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }

    // 查找并更新笔记
    const noteIndex = user.notes.findIndex(note => note._id.toString() === noteId);

    if (noteIndex === -1) {
      return res.status(404).json({ message: '笔记不存在' });
    }

    user.notes[noteIndex].content = content;
    user.notes[noteIndex].updatedAt = Date.now();

    await user.save();

    res.json({ message: '成功更新笔记', note: user.notes[noteIndex] });
  } catch (error) {
    console.error('更新笔记时出错:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

/**
 * @desc    删除笔记
 * @route   DELETE /api/users/notes/:noteId
 * @access  私有
 */
const deleteNote = async (req, res) => {
  try {
    const { noteId } = req.params;
    const user = await User.findById(req.user._id);

    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }

    // 移除笔记
    user.notes = user.notes.filter(note => note._id.toString() !== noteId);
    await user.save();

    res.json({ message: '成功删除笔记' });
  } catch (error) {
    console.error('删除笔记时出错:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

/**
 * @desc    更新学习进度
 * @route   PUT /api/users/progress
 * @access  私有
 */
const updateProgress = async (req, res) => {
  try {
    const { cardId, status, confidence } = req.body;
    const user = await User.findById(req.user._id);

    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }

    // 查找是否已有该卡片的进度记录
    const progressIndex = user.progress.findIndex(
      p => p.cardId.toString() === cardId
    );

    if (progressIndex !== -1) {
      // 更新现有进度
      if (status) user.progress[progressIndex].status = status;
      if (confidence !== undefined) user.progress[progressIndex].confidence = confidence;
      user.progress[progressIndex].lastViewed = Date.now();
    } else {
      // 添加新进度记录
      user.progress.push({
        cardId,
        status: status || 'in_progress',
        confidence: confidence || 0,
        lastViewed: Date.now()
      });
    }

    await user.save();

    res.json({ message: '成功更新学习进度', progress: user.progress });
  } catch (error) {
    console.error('更新学习进度时出错:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

/**
 * @desc    记录练习结果
 * @route   POST /api/users/exercises
 * @access  私有
 */
const recordExercise = async (req, res) => {
  try {
    const { exerciseId, correct, userAnswer } = req.body;
    const user = await User.findById(req.user._id);

    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }

    // 添加练习记录
    const exerciseRecord = {
      exerciseId,
      correct,
      userAnswer,
      attemptDate: Date.now()
    };

    user.exercises.push(exerciseRecord);
    await user.save();

    res.status(201).json({ message: '成功记录练习结果', exerciseRecord });
  } catch (error) {
    console.error('记录练习结果时出错:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

/**
 * @desc    获取学习报告
 * @route   GET /api/users/report
 * @access  私有
 */
const getLearningReport = async (req, res) => {
  try {
    const user = await User.findById(req.user._id)
      .populate('progress.cardId')
      .populate('exercises.exerciseId');

    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }

    // 生成学习报告
    const report = {
      totalCards: user.progress.length,
      completedCards: user.progress.filter(p => p.status === 'completed').length,
      averageConfidence: user.progress.reduce((sum, p) => sum + p.confidence, 0) / 
                        (user.progress.length || 1),
      totalExercises: user.exercises.length,
      correctExercises: user.exercises.filter(e => e.correct).length,
      accuracyRate: user.exercises.length > 0 ? 
                   (user.exercises.filter(e => e.correct).length / user.exercises.length) * 100 : 0,
      weakestAreas: [], // 将在下面计算
      recentActivity: user.progress
        .sort((a, b) => b.lastViewed - a.lastViewed)
        .slice(0, 5)
    };

    // 计算最薄弱的领域（基于错误率和低信心）
    const chapterPerformance = {};
    
    // 收集每个章节的练习错误
    for (const exercise of user.exercises) {
      if (exercise.exerciseId && exercise.exerciseId.cardId) {
        const card = await Card.findById(exercise.exerciseId.cardId);
        if (card) {
          if (!chapterPerformance[card.chapter]) {
            chapterPerformance[card.chapter] = { total: 0, incorrect: 0 };
          }
          chapterPerformance[card.chapter].total += 1;
          if (!exercise.correct) {
            chapterPerformance[card.chapter].incorrect += 1;
          }
        }
      }
    }
    
    // 计算每个章节的错误率
    for (const chapter in chapterPerformance) {
      if (chapterPerformance[chapter].total > 0) {
        chapterPerformance[chapter].errorRate = 
          (chapterPerformance[chapter].incorrect / chapterPerformance[chapter].total) * 100;
      }
    }
    
    // 获取错误率最高的章节
    report.weakestAreas = Object.entries(chapterPerformance)
      .sort((a, b) => b[1].errorRate - a[1].errorRate)
      .slice(0, 3)
      .map(([chapter, data]) => ({
        chapter,
        errorRate: data.errorRate,
        totalExercises: data.total
      }));

    res.json(report);
  } catch (error) {
    console.error('获取学习报告时出错:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

/**
 * @desc    清理用户数据
 * @route   DELETE /api/users/data
 * @access  私有
 */
const cleanupUserData = async (req, res) => {
  try {
    const userId = req.user._id;
    const { dataType } = req.query;
    
    // 根据请求参数清理不同类型的数据
    let result = { message: '数据清理成功' };
    
    if (!dataType || dataType === 'all') {
      // 清理所有数据
      const Document = require('../models/Document');
      const Card = require('../models/Card');
      const Exercise = require('../models/Exercise');
      const LearningPath = require('../models/LearningPath');
      const UserLearningProgress = require('../models/UserLearningProgress');
      const fileUpload = require('../utils/fileUpload');
      
      // 查找用户上传的文档
      const userDocuments = await Document.find({ uploadedBy: userId });
      const documentIds = userDocuments.map(doc => doc._id);
      
      // 删除物理文件
      for (const doc of userDocuments) {
        if (doc.filePath && fs.existsSync(doc.filePath)) {
          try {
            fs.unlinkSync(doc.filePath);
          } catch (error) {
            console.error(`删除用户文件失败: ${doc.filePath}`, error);
          }
        }
      }
      
      // 查找关联的学习路径
      const learningPaths = await LearningPath.find({ 
        $or: [
          { documentId: { $in: documentIds } },
          { createdBy: userId }
        ]
      });
      const learningPathIds = learningPaths.map(path => path._id);
      
      // 删除学习进度
      const deletedProgress = await UserLearningProgress.deleteMany({ 
        $or: [
          { userId },
          { learningPathId: { $in: learningPathIds } }
        ]
      });
      
      // 删除学习路径
      const deletedPaths = await LearningPath.deleteMany({ 
        $or: [
          { documentId: { $in: documentIds } },
          { createdBy: userId }
        ]
      });
      
      // 删除卡片
      const deletedCards = await Card.deleteMany({ sourceDocument: { $in: documentIds } });
      
      // 删除练习题
      const deletedExercises = await Exercise.deleteMany({ createdBy: userId });
      
      // 删除文档
      const deletedDocuments = await Document.deleteMany({ uploadedBy: userId });
      
      // 清理用户的书签和笔记
      const user = await User.findById(userId);
      user.bookmarks = [];
      user.notes = [];
      await user.save();
      
      // 清理孤立文件
      const orphanedFilesResult = await fileUpload.cleanupOrphanedFiles();
      
      result.details = {
        documents: deletedDocuments.deletedCount,
        cards: deletedCards.deletedCount,
        exercises: deletedExercises.deletedCount,
        learningPaths: deletedPaths.deletedCount,
        progressRecords: deletedProgress.deletedCount,
        orphanedFiles: orphanedFilesResult.deleted
      };
    } else if (dataType === 'bookmarks') {
      // 只清理书签
      const user = await User.findById(userId);
      user.bookmarks = [];
      await user.save();
      result.details = { bookmarks: '已清空' };
    } else if (dataType === 'notes') {
      // 只清理笔记
      const user = await User.findById(userId);
      user.notes = [];
      await user.save();
      result.details = { notes: '已清空' };
    } else if (dataType === 'progress') {
      // 只清理学习进度
      const UserLearningProgress = require('../models/UserLearningProgress');
      const deletedProgress = await UserLearningProgress.deleteMany({ userId });
      result.details = { progressRecords: deletedProgress.deletedCount };
    }
    
    res.json(result);
  } catch (error) {
    console.error('清理用户数据时出错:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

/**
 * @desc    获取用户数据统计
 * @route   GET /api/users/stats
 * @access  私有
 */
const getUserStats = async (req, res) => {
  try {
    const userId = req.user._id;
    
    // 引入需要的模型
    const Document = require('../models/Document');
    const Card = require('../models/Card');
    const LearningPath = require('../models/LearningPath');
    const UserLearningProgress = require('../models/UserLearningProgress');
    
    // 获取用户信息，包括书签和笔记
    const user = await User.findById(userId);
    
    // 统计用户上传的文档数量
    const documentsCount = await Document.countDocuments({ uploadedBy: userId });
    
    // 获取用户上传的所有文档ID
    const userDocuments = await Document.find({ uploadedBy: userId }, '_id');
    const documentIds = userDocuments.map(doc => doc._id);
    
    // 统计用户文档生成的卡片数量
    const cardsCount = await Card.countDocuments({ sourceDocument: { $in: documentIds } });
    
    // 统计用户创建的学习路径数量
    const learningPathsCount = await LearningPath.countDocuments({ createdBy: userId });
    
    // 统计用户的学习进度记录
    const progressCount = await UserLearningProgress.countDocuments({ userId });
    
    // 返回统计结果
    res.json({
      documents: documentsCount,
      cards: cardsCount,
      learningPaths: learningPathsCount,
      bookmarks: user.bookmarks ? user.bookmarks.length : 0,
      notes: user.notes ? user.notes.length : 0,
      progress: progressCount
    });
  } catch (error) {
    console.error('获取用户统计数据时出错:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

/**
 * @desc    获取用户笔记列表
 * @route   GET /api/users/notes
 * @access  私有
 */
const getNotes = async (req, res) => {
  try {
    const userId = req.user._id;
    
    // 获取用户信息，包括笔记
    const user = await User.findById(userId).populate({
      path: 'notes.cardId',
      select: 'title content chapter difficulty tags sourceDocument'
    });
    
    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }
    
    console.log(`[getNotes] 用户 ${userId} 的笔记数量: ${user.notes.length}`);
    
    res.json(user.notes || []);
  } catch (error) {
    console.error('获取笔记列表时出错:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

module.exports = {
  registerUser,
  loginUser,
  getUserProfile,
  updateUserProfile,
  addBookmark,
  removeBookmark,
  addNote,
  updateNote,
  deleteNote,
  updateProgress,
  recordExercise,
  getLearningReport,
  cleanupUserData,
  getUserStats,
  getBookmarks,
  getNotes
}; 